﻿using System;
using System.Linq.Expressions;

namespace Batman.Maintenance.Utils
{
    public class ExpressionUtil
    {
        /// <summary>
        /// 获取表达式返回的属性的名字
        /// </summary>
        /// <param name="property"></param>
        /// <param name="toSmallHumpWord">是否转换为小驼峰</param>
        /// <returns></returns>
        public static string GetSmallHumpWord(Expression property, bool toSmallHumpWord = true)
        {
            var result = string.Empty;

            switch (property.NodeType)
            {
                case ExpressionType.MemberAccess:
                    result = ((MemberExpression)property).Member.Name;
                    break;
                case ExpressionType.Lambda:
                    result = GetSmallHumpWord((property as LambdaExpression).Body, toSmallHumpWord);
                    break;
                case ExpressionType.Convert:
                    result = GetSmallHumpWord(((UnaryExpression)property).Operand, toSmallHumpWord);
                    break;
                default:
                    throw new NotSupportedException(property.NodeType.ToString());
            }

            if (!toSmallHumpWord) return result;
            if (string.IsNullOrEmpty(result)) return result;

            if (result.Length == 1) return result.ToLower();
            return char.ToLower(result[0]) + result.Substring(1);
        }
    }
}
